﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Data;
using System.Threading;

namespace AMS.Business
{
    public class AccessWeb
    {
        #region Member
        private readonly AccountInfoBLL accountBll = new AccountInfoBLL();
        private readonly AccessLogBLL log = new AccessLogBLL();
        private readonly MailService mailService = new MailService();
        #endregion

        #region Function
        private string AccessWebURL(string account, string password)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            string gethost = string.Empty;
            CookieContainer cc = new CookieContainer();
            string Cookiesstr = string.Empty;
            string result = "";
            try
            {
                //第一次POST请求
                //string postdata = "SESSION_TOKEN={0}&LoginType=Explicit&user=citrite%5Ct_qingangl&password=4rfv%25TGB";
                string postdata = "SESSION_TOKEN=qcsj&LoginType=Explicit&user={0}&password={1}";
                //postdata = string.Format(postdata, account, password.Replace("@", "%40"));
                postdata = string.Format(postdata, account.Replace(@"\", "%5C"), password.Replace("@", "%40"));
                string LoginUrl = System.Configuration.ConfigurationManager.AppSettings["LoginURL"];
                request = (HttpWebRequest)WebRequest.Create(LoginUrl);//实例化web访问类
                request.Method = "POST";//数据提交方式为POST
                //模拟头
                request.ContentType = "application/x-www-form-urlencoded";
                byte[] postdatabytes = Encoding.UTF8.GetBytes(postdata);
                request.ContentLength = postdatabytes.Length;
                request.AllowAutoRedirect = false;
                request.CookieContainer = cc;
                request.KeepAlive = true;
                //提交请求
                Stream stream;
                stream = request.GetRequestStream();
                stream.Write(postdatabytes, 0, postdatabytes.Length);
                stream.Close();
                //接收响应
                response = (HttpWebResponse)request.GetResponse();
                //保存返回cookie
                response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
                CookieCollection cook = response.Cookies;
                string strcrook = request.CookieContainer.GetCookieHeader(request.RequestUri);
                Cookiesstr = strcrook;
                //取第一次GET跳转地址
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string content = sr.ReadToEnd();
                response.Close();
                gethost = System.Configuration.ConfigurationManager.AppSettings["GoalURL"];
            }
            catch (Exception)
            {
                //第一次POST出错；
                result = "";
            }
            try
            {
                request = (HttpWebRequest)WebRequest.Create(gethost);
                request.Method = "GET";
                request.KeepAlive = true;
                request.Headers.Add("Cookie:" + Cookiesstr);
                request.CookieContainer = cc;
                request.AllowAutoRedirect = false;
                response = (HttpWebResponse)request.GetResponse();
                //设置cookie
                Cookiesstr = request.CookieContainer.GetCookieHeader(request.RequestUri);
                //取再次跳转链接
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd();
                request.Abort();
                sr.Close();
                response.Close();
            }

            catch (Exception)
            {
                result = "";
            }

            return result;
        }

        /// <summary>
        /// 分析网站返回数据
        /// </summary>
        /// <returns> 
        /// 0: invalid account
        /// 1: active account
        /// 2: locked account
        /// </returns>
        private int AnalyzeReponse(string result)
        {
            int iStatus = 0;
            if (string.IsNullOrEmpty(result) || result.IndexOf("login.aspx") > 0)
                iStatus = 0;
            else if (result.IndexOf("Logged on as") > 0)
                iStatus = 1;
            else if (result.IndexOf("locked.aspx") > 0)
                iStatus = 2;
            return iStatus;
        }

        /// <summary>
        /// 更新数据库
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        private void UpdateAccountStatus(string ID, string account, string password,string to, string cc)
        {
            string result = AccessWebURL(account, password);
            int iStatus = AnalyzeReponse(result);
            int affectRow = accountBll.UpdateAccountStatus(ID, iStatus);
            if (affectRow == 1)
            {
                log.AddAcessLog(ID, iStatus);
            }
            if (iStatus == 2)
            {
                mailService.CreateMail("001", cc, to, null, null);
            }
        }

        /// <summary>
        /// 批量访问数据
        /// </summary>
        public void BatchAccessWeb()
        {
            DataTable dt = accountBll.GetAllAccountInfo();
            foreach (DataRow row in dt.Rows)
            {
                string id = row["ID"].ToString().Trim();
                string account = row["AccountName"].ToString().Trim();
                string password = row["Password"].ToString().Trim();
                string to = row["Email"].ToString().Trim();
                string cc = row["CCEmail"].ToString().Trim();
                UpdateAccountStatus(id, account, password, to, cc);
                Thread.Sleep(100);
            }
            //UpdateAccountStatus(Guid.NewGuid().ToString(), @"citrite\t_runpuz", "$RFV5tgb", "xingbiao.gu@hisoft.com", "");
        }
        #endregion
    }
}
